﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.HSSF.UserModel;
using System.IO;
using NPOI.SS.UserModel;
using ProjectSchedule.Entity;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using NPOI.HSSF.Util;
using System.Windows.Forms;

namespace ProjectSchedule.Common
{
    public static class ExcelOperation
    {
        public static readonly string BaseDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
        public static readonly string CurrentDirectory = BaseDirectory.EndsWith("\\")
                                                       ? BaseDirectory.Remove(BaseDirectory.Length - 1)
                                                       : BaseDirectory;
        /// <summary>
        /// 读取Excel源文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static CTSchedule ReadExcel_CT(string filePath)
        {
            HSSFWorkbook workbook;
            LogHelper.Info("开始读取中日程计划（船体），文件名：" + filePath);
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                workbook = new HSSFWorkbook(file);
                file.Close();
            }
            LogHelper.Info("结束读取中日程计划（船体），文件名：" + filePath);

            ISheet Sheet1 = workbook.GetSheet("调整表");
            ISheet Sheet2 = workbook.GetSheet("分段工期表");
            ISheet Sheet3 = workbook.GetSheet("工序单位表");
            ISheet Sheet4 = workbook.GetSheet("中合A搭载表");
            ISheet Sheet5 = workbook.GetSheet("中合B搭载表");

            if (Sheet2 == null)
            {
                return null;
            }

            #region  ==船体
            IList<CTAdjustment> Adjustments = new List<CTAdjustment>();
            for (int i = 0; i <= Sheet1.LastRowNum; i++)
            {
                var row = Sheet1.GetRow(i);
                if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                Adjustments.Add(new CTAdjustment
                {
                    ShipName = row.GetStringCellValue(0),
                    SectionName = row.GetStringCellValue(1),
                    Weight = row.GetNumericCellValue(2),
                    LargeMergeTime = row.GetDateCellValue(3),
                });
            }

            IList<CTSectionTime> SectionTimes = new List<CTSectionTime>();
            for (int i = 0; i <= Sheet2.LastRowNum; i++)
            {
                var row = Sheet2.GetRow(i);
                if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                SectionTimes.Add(new CTSectionTime
                {
                    ShipName = row.GetStringCellValue(0),
                    SectionName = row.GetStringCellValue(1),
                    Pretreat = Convert.ToInt32(row.GetNumericCellValue(2)),
                    PretreatInterval = Convert.ToInt32(row.GetNumericCellValue(3)),
                    Cutting = Convert.ToInt32(row.GetNumericCellValue(4)),
                    CuttingInterval = Convert.ToInt32(row.GetNumericCellValue(5)),
                    SmallGroup = Convert.ToInt32(row.GetNumericCellValue(6)),
                    SmallGroupInterval = Convert.ToInt32(row.GetNumericCellValue(7)),
                    MediumGroup = Convert.ToInt32(row.GetNumericCellValue(8)),
                    MediumGroupInterval = Convert.ToInt32(row.GetNumericCellValue(9)),
                    MediumMergeA = Convert.ToInt32(row.GetNumericCellValue(10)),
                    MediumMergeAInterval = Convert.ToInt32(row.GetNumericCellValue(11)),
                    MediumPainting = Convert.ToInt32(row.GetNumericCellValue(12)),
                    MediumPaintingInterval = Convert.ToInt32(row.GetNumericCellValue(13)),
                    MediumMergeB = Convert.ToInt32(row.GetNumericCellValue(14)),
                    MediumMergeBInterval = Convert.ToInt32(row.GetNumericCellValue(15)),
                    LargeMerge = Convert.ToInt32(row.GetNumericCellValue(16)),
                    LargeMergeInterval = Convert.ToInt32(row.GetNumericCellValue(17)),
                    TrialTrip = Convert.ToInt32(row.GetNumericCellValue(18)),
                    TrialTripInterval = Convert.ToInt32(row.GetNumericCellValue(19)),
                });
            }

            IList<CTProcessUnit> ProcessUnits = new List<CTProcessUnit>();
            for (int i = 0; i <= Sheet3.LastRowNum; i++)
            {
                var row = Sheet3.GetRow(i);
                if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                ProcessUnits.Add(new CTProcessUnit
                {
                    ShipName = row.GetStringCellValue(0),
                    SectionName = row.GetStringCellValue(1),
                    DealUnit = row.GetStringCellValue(2),
                    CuttUnit = row.GetStringCellValue(3),
                    SmallGroupUnit = row.GetStringCellValue(4),
                    MedGroupUnit = row.GetStringCellValue(5),
                    MedAUnit = row.GetStringCellValue(6),
                    MidPaintUnit = row.GetStringCellValue(7),
                    MedBUnit = row.GetStringCellValue(6),
                    BigUnit = row.GetStringCellValue(8)
                });
            }

            IList<MediumMergeRelate> mARelates = new List<MediumMergeRelate>();
            for (int i = 0; i <= Sheet4.LastRowNum; i++)
            {
                var row = Sheet4.GetRow(i);
                if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                mARelates.Add(new MediumMergeRelate
                {
                    ShipName = row.GetCell(0).ToString(),
                    MediumMergeName = row.GetStringCellValue(1)
                });
            }
            IList<MediumMergeRelate> mBRelates = new List<MediumMergeRelate>();
            for (int i = 0; i <= Sheet5.LastRowNum; i++)
            {
                var row = Sheet5.GetRow(i);
                if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                mBRelates.Add(new MediumMergeRelate
                {
                    ShipName = row.GetCell(0).ToString(),
                    MediumMergeName = row.GetStringCellValue(1)
                });
            }
            #endregion

            LogHelper.Info("读取船体数据成功！ " + filePath);
            return new CTSchedule
            {
                Adjustments = Adjustments,
                ProcessUnits = ProcessUnits,
                SectionTimes = SectionTimes,
                MediumMergeARelates = mARelates,
                MediumMergeBRelates = mBRelates
            };
        }

        public static XZSchedule ReadExcel_XZ(string filePath)
        {
            HSSFWorkbook workbook;
            LogHelper.Info("开始读取中日程计划（舾装），文件名：" + filePath);
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                workbook = new HSSFWorkbook(file);
                file.Close();
            }
            LogHelper.Info("结束读取中日程计划（舾装），文件名：" + filePath);

            ISheet Sheet1 = workbook.GetSheet("调整表（区域）");
            ISheet Sheet2 = workbook.GetSheet("区域工期表");
            ISheet Sheet3 = workbook.GetSheet("工序单位表（区域）");

            ISheet Sheet4 = workbook.GetSheet("调整表（分段）");
            ISheet Sheet5 = workbook.GetSheet("分段工期表");
            ISheet Sheet6 = workbook.GetSheet("工序单位表（分段）");

            ISheet Sheet7 = workbook.GetSheet("调整表（调试）");
            ISheet Sheet8 = workbook.GetSheet("调试工期表");
            ISheet Sheet9 = workbook.GetSheet("工序单位表（调试）");

            if (Sheet2 == null && Sheet5 == null && Sheet8==null)
            {
                return null;
            }

            #region ==舾装

            IList<XZAdjustment_Area> Adjustments_Area = new List<XZAdjustment_Area>();
            IList<XZSectionTime_Area> SectionTimes_Area = new List<XZSectionTime_Area>();
            IList<XZProcessUnit_Area> ProcessUnits_Area = new List<XZProcessUnit_Area>();
            IList<XZAdjustment_Section> Adjustments_Section = new List<XZAdjustment_Section>();
            IList<XZSectionTime_Section> SectionTimes_Section = new List<XZSectionTime_Section>();
            IList<XZProcessUnit_Section> ProcessUnits_Section = new List<XZProcessUnit_Section>();
            IList<XZAdjustment_Debug> Adjustments_Debug = new List<XZAdjustment_Debug>();
            IList<XZSectionTime_Debug> SectionTimes_Debug = new List<XZSectionTime_Debug>();
            IList<XZProcessUnit_Debug> ProcessUnits_Debug = new List<XZProcessUnit_Debug>();

            if (Sheet2 != null)
            {
                for (int i = 0; i <= Sheet1.LastRowNum; i++)
                {
                    var row = Sheet1.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    Adjustments_Area.Add(new XZAdjustment_Area
                    {
                        ShipName = row.GetStringCellValue(0),
                        AreaName = row.GetStringCellValue(1),
                        Weight = row.GetNumericCellValue(2),
                        BulkStartTime = row.GetDateCellValue(3)
                    });
                }

                for (int i = 0; i <= Sheet2.LastRowNum; i++)
                {
                    var row = Sheet2.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    SectionTimes_Area.Add(new XZSectionTime_Area
                    {
                        ShipName = row.GetStringCellValue(0),
                        AreaName = row.GetStringCellValue(1),
                        Cutting = Convert.ToInt32(row.GetNumericCellValue(2)),
                        CuttingInterval = Convert.ToInt32(row.GetNumericCellValue(3)),
                        Molding = Convert.ToInt32(row.GetNumericCellValue(4)),
                        MoldingInterval = Convert.ToInt32(row.GetNumericCellValue(5)),
                        Weld = Convert.ToInt32(row.GetNumericCellValue(6)),
                        WeldInterval = Convert.ToInt32(row.GetNumericCellValue(7)),
                        Polish = Convert.ToInt32(row.GetNumericCellValue(8)),
                        PolishInterval = Convert.ToInt32(row.GetNumericCellValue(9)),
                        Intest = Convert.ToInt32(row.GetNumericCellValue(10)),
                        IntestInterval = Convert.ToInt32(row.GetNumericCellValue(11)),
                        Pretreat = Convert.ToInt32(row.GetNumericCellValue(12)),
                        PretreatInterval = Convert.ToInt32(row.GetNumericCellValue(13)),
                        Bulk = Convert.ToInt32(row.GetNumericCellValue(14)),
                        BulkInterval = Convert.ToInt32(row.GetNumericCellValue(15)),
                        DockProject = Convert.ToInt32(row.GetNumericCellValue(16)),
                        DockProjectInterval = Convert.ToInt32(row.GetNumericCellValue(17)),
                        TrialTrip = Convert.ToInt32(row.GetNumericCellValue(18)),
                        TrialTripInterval = Convert.ToInt32(row.GetNumericCellValue(19)),
                        Delivery = Convert.ToInt32(row.GetNumericCellValue(20)),
                        DeliveryInterval = Convert.ToInt32(row.GetNumericCellValue(21))
                    });
                }

                for (int i = 0; i <= Sheet3.LastRowNum; i++)
                {
                    var row = Sheet3.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    ProcessUnits_Area.Add(new XZProcessUnit_Area
                    {
                        ShipName = row.GetStringCellValue(0),
                        AreaName = row.GetStringCellValue(1),

                        CuttUnit = row.GetStringCellValue(2),
                        MoldingUnit = row.GetStringCellValue(3),
                        WeldUnit = row.GetStringCellValue(4),
                        PolishUnit = row.GetStringCellValue(5),
                        IntestUnit = row.GetStringCellValue(6),
                        BulkUnit = row.GetStringCellValue(7),
                        DockProjectUnit = row.GetStringCellValue(8),
                        TrialTripUnit = row.GetStringCellValue(9),
                        DeliveryUnit = row.GetStringCellValue(10),
                        PretreatUnit = row.GetStringCellValue(11)
                    });
                }
            }

            if (Sheet5 != null)
            {
                for (int i = 0; i <= Sheet4.LastRowNum; i++)
                {
                    var row = Sheet4.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    Adjustments_Section.Add(new XZAdjustment_Section
                    {
                        ShipName = row.GetStringCellValue(0),
                        SectionName = row.GetStringCellValue(1),
                        Weight = row.GetNumericCellValue(2),
                        PreassembleStopTime = row.GetDateCellValue(3)
                    });
                }

                for (int i = 0; i <= Sheet5.LastRowNum; i++)
                {
                    var row = Sheet5.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    SectionTimes_Section.Add(new XZSectionTime_Section
                    {
                        ShipName = row.GetStringCellValue(0),
                        SectionName = row.GetStringCellValue(1),
                        Cutting = Convert.ToInt32(row.GetNumericCellValue(2)),
                        CuttingInterval = Convert.ToInt32(row.GetNumericCellValue(3)),
                        Molding = Convert.ToInt32(row.GetNumericCellValue(4)),
                        MoldingInterval = Convert.ToInt32(row.GetNumericCellValue(5)),
                        Weld = Convert.ToInt32(row.GetNumericCellValue(6)),
                        WeldInterval = Convert.ToInt32(row.GetNumericCellValue(7)),
                        Polish = Convert.ToInt32(row.GetNumericCellValue(8)),
                        PolishInterval = Convert.ToInt32(row.GetNumericCellValue(9)),
                        Intest = Convert.ToInt32(row.GetNumericCellValue(10)),
                        IntestInterval = Convert.ToInt32(row.GetNumericCellValue(11)),
                        Pretreat = Convert.ToInt32(row.GetNumericCellValue(12)),
                        PretreatInterval = Convert.ToInt32(row.GetNumericCellValue(13)),
                        Preassemble = Convert.ToInt32(row.GetNumericCellValue(14)),
                        PreassembleInterval = Convert.ToInt32(row.GetNumericCellValue(15))
                    });
                }

                for (int i = 0; i <= Sheet6.LastRowNum; i++)
                {
                    var row = Sheet6.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    ProcessUnits_Section.Add(new XZProcessUnit_Section
                    {
                        ShipName = row.GetStringCellValue(0),
                        SectionName = row.GetStringCellValue(1),
                        PretreatUnit = row.GetStringCellValue(2),
                        CuttUnit = row.GetStringCellValue(3),
                        MoldingUnit = row.GetStringCellValue(4),
                        WeldUnit = row.GetStringCellValue(5),
                        PolishUnit = row.GetStringCellValue(6),
                        IntestUnit = row.GetStringCellValue(7),
                        PreassembleUnit = row.GetStringCellValue(8)
                    });
                }
            }

            if (Sheet8 != null)
            {

                for (int i = 0; i <= Sheet7.LastRowNum; i++)
                {
                    var row = Sheet7.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    Adjustments_Debug.Add(new XZAdjustment_Debug
                    {
                        ShipName = row.GetStringCellValue(0),
                        ProjectName = row.GetStringCellValue(1),
                        DebugedTime = row.GetDateCellValue(2)
                    });
                }
                
                for (int i = 0; i <= Sheet8.LastRowNum; i++)
                {
                    var row = Sheet8.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    SectionTimes_Debug.Add(new XZSectionTime_Debug
                    {
                        ShipName = row.GetStringCellValue(0),
                        ProjectName = row.GetStringCellValue(1),
                        Debugging = Convert.ToInt32(row.GetNumericCellValue(2)),
                        DebuggingInterval = Convert.ToInt32(row.GetNumericCellValue(3)),
                    });
                }

                
                for (int i = 0; i <= Sheet9.LastRowNum; i++)
                {
                    var row = Sheet9.GetRow(i);
                    if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                    ProcessUnits_Debug.Add(new XZProcessUnit_Debug
                    {
                        ShipName = row.GetStringCellValue(0),
                        ProjectName = row.GetStringCellValue(1),
                        DebuggingUnit = row.GetStringCellValue(2)
                    });
                }
            }

            #endregion
            LogHelper.Info("读取舾装数据成功！ " + filePath);
            return new XZSchedule
            {
                Adjustments_Area = Adjustments_Area,
                SectionTimes_Area = SectionTimes_Area,
                ProcessUnits_Area = ProcessUnits_Area,
                Adjustments_Section = Adjustments_Section,
                SectionTimes_Section = SectionTimes_Section,
                ProcessUnits_Section = ProcessUnits_Section,
                Adjustments_Debug = Adjustments_Debug,
                SectionTimes_Debug = SectionTimes_Debug,
                ProcessUnits_Debug = ProcessUnits_Debug
            };
        }

        public static TWSchedule ReadExcel_TW(string filePath)
        {
            HSSFWorkbook workbook;
            LogHelper.Info("开始读取胎位分段数据，文件名：" + filePath);
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                workbook = new HSSFWorkbook(file);
                file.Close();
            }
            LogHelper.Info("结束读取胎位分段数据，文件名：" + filePath);
            ISheet Sheet1 = workbook.GetSheet("胎位信息表");
            ISheet Sheet2 = workbook.GetSheet("分段信息表");
            if (Sheet1 == null || Sheet2 == null) {
                return null;
            }
            IList<TWBasicInfo> TWBasic = new List<TWBasicInfo>();
            for (int i = 0; i <= Sheet1.LastRowNum; i++)
            {
                var row = Sheet1.GetRow(i);
                if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                TWBasic.Add(new TWBasicInfo { 
                    ID = Convert.ToInt32(row.GetStringCellValue(0)),
                    Position = row.GetStringCellValue(1),
                    Long = Convert.ToInt32(row.GetStringCellValue(2).Split('*')[0]),
                    Width = Convert.ToInt32(row.GetStringCellValue(2).Split('*')[1]),
                    Height = Convert.ToInt32(row.GetStringCellValue(2).Split('*')[2]),
                    HangingHeight = Convert.ToInt32(row.GetNumericCellValue(3))
                });
            }
            IList<TWSectionInfo> TWSection = new List<TWSectionInfo>();
            for (int i = 0; i <= Sheet2.LastRowNum; i++)
            {
                var row = Sheet2.GetRow(i);
                if (i < 1 || row == null || row.GetCell(0) == null || String.IsNullOrEmpty(row.GetStringCellValue(0))) continue;
                TWSection.Add(new TWSectionInfo { 
                    ID = Convert.ToInt32(row.GetStringCellValue(0)),
                    ShipName = row.GetStringCellValue(1),
                    SectionName = row.GetStringCellValue(2),
                    UpFetalDate = Convert.ToDateTime(row.GetDateCellValue(3)),
                    DownFetalDate = Convert.ToDateTime(row.GetDateCellValue(4)),
                    Long = Convert.ToSingle(row.GetStringCellValue(5).Split('*')[0]),
                    Width = Convert.ToSingle(row.GetStringCellValue(5).Split('*')[1]),
                    Height = Convert.ToSingle(row.GetStringCellValue(5).Split('*')[2])
                });
            };
            LogHelper.Info("读取胎位分段数据成功！ " + filePath);
            return new TWSchedule
            {
                BasicInfos = TWBasic,
                SectionInfos = TWSection
            };
        }

        /// <summary>
        /// 导出汇总表
        /// </summary>
        /// <param name="saveFileName"></param>
        /// <param name="Plans"></param>
        public static bool SaveSummary_CT(string saveFileName, CTSchedule schedule)
        {
            try
            {
                LogHelper.Info("导出船体汇总表开始");
                var SummaryTemplate = CurrentDirectory + @"\Template\生成汇总（船体）.xls";
                if (!File.Exists(SummaryTemplate))
                {
                    LogHelper.Error("船体汇总模板不存在，文件名：" + saveFileName);
                    MessageBox.Show("船体汇总模板不存在！", "提示");
                    return false;
                }
                var Plans = ConvertToCTPlan(schedule);

                HSSFWorkbook workbook;
                LogHelper.Info("开始读取船体汇总模板，文件名：" + SummaryTemplate);
                using (FileStream file = new FileStream(SummaryTemplate, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                    file.Close();
                }
                LogHelper.Info("结束保存船体汇总模板，文件名：" + SummaryTemplate);

                var Sheet1 = workbook.GetSheet("分段计划表");
                for (var i = 0; i < Plans.Count; i++)
                {
                    var row = Sheet1.CreateRow(i + 1);
                    row.CreateCell(0).SetCellValue(Plans[i].ShipName);
                    row.CreateCell(1).SetCellValue(Plans[i].SectionName);
                    row.CreateCell(2).SetCellValue(Plans[i].Weight);

                    var cell3 = row.CreateCell(3);
                    cell3.SetCellValue(Plans[i].PretreatStart.HasValue
                          ? Plans[i].PretreatStart.Value.ToString("yyyy-MM-dd")
                          : String.Empty);

                    var cell4 = row.CreateCell(4);
                    cell4.SetCellValue(Plans[i].PretreatStop.HasValue
                         ? Plans[i].PretreatStop.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell5 = row.CreateCell(5);
                    cell5.SetCellValue(Plans[i].CuttingStart.HasValue
                         ? Plans[i].CuttingStart.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell6 = row.CreateCell(6);
                    cell6.SetCellValue(Plans[i].CuttingStop.HasValue
                         ? Plans[i].CuttingStop.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell7 = row.CreateCell(7);
                    cell7.SetCellValue(Plans[i].SmallGroupStart.HasValue
                         ? Plans[i].SmallGroupStart.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell8 = row.CreateCell(8);
                    cell8.SetCellValue(Plans[i].SmallGroupStop.HasValue
                         ? Plans[i].SmallGroupStop.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell9 = row.CreateCell(9);
                    cell9.SetCellValue(Plans[i].MediumGroupStart.HasValue
                         ? Plans[i].MediumGroupStart.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell10 = row.CreateCell(10);
                    cell10.SetCellValue(Plans[i].MediumGroupStop.HasValue
                         ? Plans[i].MediumGroupStop.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell11 = row.CreateCell(11);
                    cell11.SetCellValue(Plans[i].MediumMergeAStart.HasValue
                         ? Plans[i].MediumMergeAStart.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell12 = row.CreateCell(12);
                    cell12.SetCellValue(Plans[i].MediumMergeAStop.HasValue
                         ? Plans[i].MediumMergeAStop.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell13 = row.CreateCell(13);
                    cell13.SetCellValue(Plans[i].MediumPaintingStart.HasValue
                         ? Plans[i].MediumPaintingStart.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell14 = row.CreateCell(14);
                    cell14.SetCellValue(Plans[i].MediumPaintingStop.HasValue
                         ? Plans[i].MediumPaintingStop.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell15 = row.CreateCell(15);
                    cell15.SetCellValue(Plans[i].MediumMergeBStart.HasValue
                         ? Plans[i].MediumMergeBStart.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell16 = row.CreateCell(16);
                    cell16.SetCellValue(Plans[i].MediumMergeBStop.HasValue
                         ? Plans[i].MediumMergeBStop.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell17 = row.CreateCell(17);
                    cell17.SetCellValue(Plans[i].LargeMergeStart.HasValue
                         ? Plans[i].LargeMergeStart.Value.ToString("yyyy-MM-dd")
                         : String.Empty);

                    var cell18 = row.CreateCell(18);
                    cell18.SetCellValue(Plans[i].LargeMergeStop.HasValue
                         ? Plans[i].LargeMergeStop.Value.ToString("yyyy-MM-dd")
                         : String.Empty);
                }

                if (!Directory.Exists(ExcelOperation.CurrentDirectory + "/Export"))
                {
                    Directory.CreateDirectory(ExcelOperation.CurrentDirectory + "/Export");
                }
                LogHelper.Info("开始保存船体汇总，文件名：" + saveFileName);
                //Write the stream data of workbook to the save directory
                using (FileStream exportFile = new FileStream(saveFileName, FileMode.Create))
                {
                    workbook.Write(exportFile);
                    exportFile.Close();
                }
                LogHelper.Info("结束保存船体汇总，文件名：" + saveFileName);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("导出船体汇总失败：", ex);
                return false;
            }
        }

        public static bool SaveSummary_XZ(string saveFileName, XZSchedule schedule)
        {
            try
            {
                LogHelper.Info("导出舾装汇总表开始");
                var SummaryTemplate = CurrentDirectory + @"\Template\生成汇总（舾装）.xls";
                if (!File.Exists(SummaryTemplate))
                {
                    LogHelper.Error("舾装汇总模板不存在，文件名：" + saveFileName);
                    MessageBox.Show("舾装汇总模板不存在！", "提示");
                    return false;
                }
                var SectionPlans = ConvertToXZPlan_Section(schedule);
                var AreaPlans = ConvertToXZPlan_Area(schedule);
                var DebugPlans = ConvertToXZPlan_Debug(schedule);

                HSSFWorkbook workbook;
                LogHelper.Info("开始读取舾装汇总模板，文件名：" + SummaryTemplate);
                using (FileStream file = new FileStream(SummaryTemplate, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                    file.Close();
                }
                LogHelper.Info("结束读取舾装汇总模板，文件名：" + SummaryTemplate);

                var Sheet1 = workbook.GetSheet("分段计划表");
                for (var i = 0; i < SectionPlans.Count; i++)
                {
                    var row = Sheet1.CreateRow(i + 1);
                    row.CreateCell(0).SetCellValue(SectionPlans[i].ShipName);
                    row.CreateCell(1).SetCellValue(SectionPlans[i].SectionName);
                    row.CreateCell(2).SetCellValue(SectionPlans[i].Weight);

                    row.CreateCell(3).SetCellValue(SectionPlans[i].CuttingStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(4).SetCellValue(SectionPlans[i].CuttingStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(5).SetCellValue(SectionPlans[i].MoldingStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(6).SetCellValue(SectionPlans[i].MoldingStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(7).SetCellValue(SectionPlans[i].WeldStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(8).SetCellValue(SectionPlans[i].WeldStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(9).SetCellValue(SectionPlans[i].PolishStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(10).SetCellValue(SectionPlans[i].PolishStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(11).SetCellValue(SectionPlans[i].PretreatStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(12).SetCellValue(SectionPlans[i].PretreatStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(13).SetCellValue(SectionPlans[i].IntestStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(14).SetCellValue(SectionPlans[i].IntestStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(15).SetCellValue(SectionPlans[i].PreassembleStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(16).SetCellValue(SectionPlans[i].PreassembleStop.ToString("yyyy-MM-dd"));

                }

                var Sheet2 = workbook.GetSheet("区域计划表");
                for (var i = 0; i < AreaPlans.Count; i++)
                {
                    var row = Sheet2.CreateRow(i + 1);
                    row.CreateCell(0).SetCellValue(AreaPlans[i].ShipName);
                    row.CreateCell(1).SetCellValue(AreaPlans[i].AreaName);
                    row.CreateCell(2).SetCellValue(AreaPlans[i].Weight);

                    row.CreateCell(3).SetCellValue(AreaPlans[i].CuttingStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(4).SetCellValue(AreaPlans[i].CuttingStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(5).SetCellValue(AreaPlans[i].MoldingStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(6).SetCellValue(AreaPlans[i].MoldingStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(7).SetCellValue(AreaPlans[i].WeldStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(8).SetCellValue(AreaPlans[i].WeldStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(9).SetCellValue(AreaPlans[i].PolishStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(10).SetCellValue(AreaPlans[i].PolishStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(11).SetCellValue(AreaPlans[i].IntestStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(12).SetCellValue(AreaPlans[i].IntestStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(13).SetCellValue(AreaPlans[i].PretreatStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(14).SetCellValue(AreaPlans[i].PretreatStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(15).SetCellValue(AreaPlans[i].BulkStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(16).SetCellValue(AreaPlans[i].BulkStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(17).SetCellValue(AreaPlans[i].DockProjectStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(18).SetCellValue(AreaPlans[i].DockProjectStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(19).SetCellValue(AreaPlans[i].TrialTripStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(20).SetCellValue(AreaPlans[i].TrialTripStop.ToString("yyyy-MM-dd"));

                    row.CreateCell(21).SetCellValue(AreaPlans[i].Delivery.ToString("yyyy-MM-dd"));

                }
                var Sheet3 = workbook.GetSheet("调试计划表");
                for (var i = 0; i < DebugPlans.Count; i++)
                {
                    var row = Sheet3.CreateRow(i + 1);
                    row.CreateCell(0).SetCellValue(DebugPlans[i].ShipName);
                    row.CreateCell(1).SetCellValue(DebugPlans[i].ProjectName);

                    row.CreateCell(2).SetCellValue(DebugPlans[i].DebuggingStart.ToString("yyyy-MM-dd"));
                    row.CreateCell(3).SetCellValue(DebugPlans[i].DebuggingStop.ToString("yyyy-MM-dd"));
                }

                if (!Directory.Exists(ExcelOperation.CurrentDirectory + "/Export"))
                {
                    Directory.CreateDirectory(ExcelOperation.CurrentDirectory + "/Export");
                }
                LogHelper.Info("开始保存船体汇总 " + saveFileName);
                //Write the stream data of workbook to the save directory
                using (FileStream exportFile = new FileStream(saveFileName, FileMode.Create))
                {
                    workbook.Write(exportFile);
                    exportFile.Close();
                }
                LogHelper.Info("结束保存船体汇总 " + saveFileName);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("导出舾装汇总失败：", ex);
                return false;
            }
        }

        private static IList<CTSectionPlan> ConvertToCTPlan(CTSchedule schedule)
        {
            IList<CTSectionPlan> SectionPlans = new List<CTSectionPlan>();
            foreach (var SectionTime in schedule.SectionTimes)
            {
                var d = schedule.Adjustments.Where(m => m.ShipName.Equals(SectionTime.ShipName)
                    && m.SectionName.Equals(SectionTime.SectionName)).LastOrDefault();
                if (d != null)
                {
                    var plan = new CTSectionPlan(d.LargeMergeTime, SectionTime);
                    plan.Weight = d.Weight;
                    plan.Units = schedule.ProcessUnits.Where(m => m.SectionName.Equals(SectionTime.SectionName)).FirstOrDefault();
                    SectionPlans.Add(plan);
                }
            }
            return SectionPlans;
        }

        private static IList<XZSectionPlan_Section> ConvertToXZPlan_Section(XZSchedule schedule)
        {
            IList<XZSectionPlan_Section> SectionPlans = new List<XZSectionPlan_Section>();
            foreach (var SectionTime in schedule.SectionTimes_Section)
            {
                var d = schedule.Adjustments_Section.Where(m => m.ShipName.Equals(SectionTime.ShipName)
                    && m.SectionName.Equals(SectionTime.SectionName)).LastOrDefault();
                if (d != null)
                {
                    var plan = new XZSectionPlan_Section(d.PreassembleStopTime, SectionTime);
                    plan.Weight = d.Weight;
                    plan.Units = schedule.ProcessUnits_Section.Where(m => m.SectionName.Equals(SectionTime.SectionName)).FirstOrDefault();
                    SectionPlans.Add(plan);
                }
            }
            return SectionPlans;
        }

        private static IList<XZSectionPlan_Area> ConvertToXZPlan_Area(XZSchedule schedule)
        {
            IList<XZSectionPlan_Area> AreaPlans = new List<XZSectionPlan_Area>();
            foreach (var AreaTime in schedule.SectionTimes_Area)
            {
                var d = schedule.Adjustments_Area.Where(m => m.ShipName.Equals(AreaTime.ShipName)
                    && m.AreaName.Equals(AreaTime.AreaName)).LastOrDefault();
                if (d != null)
                {
                    var plan = new XZSectionPlan_Area(d.BulkStartTime, AreaTime);
                    plan.Weight = d.Weight;
                    plan.Units = schedule.ProcessUnits_Area.Where(m => m.AreaName.Equals(AreaTime.AreaName)).FirstOrDefault();
                    AreaPlans.Add(plan);
                }
            }
            var date = AreaPlans.OrderByDescending(m => m.BulkStop).FirstOrDefault();
            foreach (var p in AreaPlans)
            {
                p.DockProjectStart = date.DockProjectStart;
                p.DockProjectStop = date.DockProjectStop;
                p.TrialTripStart = date.TrialTripStart;
                p.TrialTripStop = date.TrialTripStop;
                p.Delivery = date.Delivery;
            }
            return AreaPlans;
        }

        private static IList<XZSectionPlan_Debug> ConvertToXZPlan_Debug(XZSchedule schedule)
        {
            IList<XZSectionPlan_Debug> DebugPlans = new List<XZSectionPlan_Debug>();
            foreach (var DebugTime in schedule.SectionTimes_Debug)
            {
                var d = schedule.Adjustments_Debug.Where(m => m.ShipName.Equals(DebugTime.ShipName)
                    && m.ProjectName.Equals(DebugTime.ProjectName)).LastOrDefault();
                if (d != null)
                {
                    var plan = new XZSectionPlan_Debug(d.DebugedTime, DebugTime);
                    plan.Units = schedule.ProcessUnits_Debug.Where(m => m.ProjectName.Equals(DebugTime.ProjectName)).FirstOrDefault();
                    DebugPlans.Add(plan);
                }
            }
            return DebugPlans;
        }

        /// <summary>
        /// 导出计划表
        /// </summary>
        /// <param name="saveFileName"></param>
        /// <param name="schedule"></param>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public static bool SaveCTPlan(string saveFileName, CTSchedule schedule, Int32 year, Int32 month)
        {
            try
            {
                LogHelper.Info("导出船体计划表开始，" + year + "年" + month + "月");
                var PlanTemplate = CurrentDirectory + @"\Template\生成计划（船体）.xls";
                if (!File.Exists(PlanTemplate))
                {
                    LogHelper.Error("船体计划模板不存在，文件名：" + saveFileName);
                    MessageBox.Show("船体计划模板不存在！", "提示");
                    return false;
                }
                IList<CTSectionPlan> Plans = ConvertToCTPlan(schedule);
                var StartDate = new DateTime(year, month, 1);
                var EndDate = new DateTime(year, month, DateTime.DaysInMonth(year, month));
                var ShipName = Plans.Count > 0 ? Plans.FirstOrDefault().ShipName : String.Empty;

                HSSFWorkbook workbook;
                LogHelper.Info("开始读取船体计划模板，文件名：" + PlanTemplate);
                using (FileStream file = new FileStream(PlanTemplate, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                    file.Close();
                }
                LogHelper.Info("结束读取船体计划模板，文件名：" + PlanTemplate);
                Func<ISheet, IList<SheetUnit>> GetUnitNames = (sheet) =>
                {
                    var Names = new List<SheetUnit>();
                    var row = sheet.GetRow(1);
                    for (int i = 0; i <= 5; i++)
                    {
                        if (row.GetCell(i * 6 + 1) != null)
                            Names.Add(new SheetUnit { value = row.GetCell(i * 6 + 1).ToString(), cellnum = i * 6 + 1 });
                    }
                    return Names;
                };

                IList<CTSectionProgress> currentData = new List<CTSectionProgress>();
                IList<SheetUnit> currentUnit = new List<SheetUnit>();
                IEnumerable<string> currentSectionNames = new List<string>();

                #region LoadData
                Action<IList<CTSectionProgress>, ISheet> LoadData = (list, sheet) =>
                {
                    var dict = new CTProcessPlanDict(list);
                    if (dict.Length > 0)
                    {
                        Int32 index = 0;
                        String title1 = String.Empty;
                        String title2 = String.Empty;
                        foreach (var data in dict.Dicts)
                        {
                            if (index == 0)
                            {
                                title1 = sheet.GetRow(index).GetCell(0).ToString();
                                title2 = sheet.GetRow(index + 1).GetCell(1).ToString();
                            }
                            else
                            {
                                #region 创建标题栏
                                var hrow1 = sheet.CreateRow(index);
                                hrow1.HeightInPoints = 27.75f;
                                hrow1.CreateCell(0).SetTitleStyle(workbook.CreateCellStyle(), workbook.CreateFont());
                                hrow1.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false);
                                var hrow2 = sheet.CreateRow(index + 1);
                                hrow2.HeightInPoints = 20;
                                hrow2.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false);
                                var hrow3 = sheet.CreateRow(index + 2);
                                hrow3.HeightInPoints = 20;
                                hrow3.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow3.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("分段名");
                                hrow3.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("重量");
                                hrow3.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("开工日");
                                hrow3.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("%");
                                hrow3.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("完工日");
                                hrow3.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("%");
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index, index, 0, 6));
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index + 1, index + 2, 0, 0));
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index + 1, index + 1, 1, 6));
                                hrow2.GetCell(0).SetCellValue("工程号");
                                #endregion
                            }
                            sheet.GetRow(index++).GetCell(0).SetCellValue(String.Format(title1, year, month));
                            sheet.GetRow(index++).GetCell(1).SetCellValue(String.Format(title2, data.Key));
                            Int32 startIndex = ++index;
                            for (int i = 0; i < data.Value.Data.Count; i++)
                            {
                                var row = sheet.CreateRow(index++);
                                var d1 = data.Value.Data[i];
                                row.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);

                                row.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.SectionName);
                                row.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.Weight);
                                row.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.BeginDate.ToString("yyyy-MM-dd"));
                                row.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.BeginPrecent);
                                row.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.EndDate.ToString("yyyy-MM-dd"));
                                row.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.EndPrecent);
                            }
                            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(startIndex, index - 1, 0, 0));
                            sheet.GetRow(startIndex).GetCell(0).SetCellValue(ShipName);
                            index++;
                            if (data.Value.Data.Count > 0)
                            {
                                var tRow1 = sheet.CreateRow(index++);
                                var bRow1 = sheet.CreateRow(index++);
                                tRow1.CreateCell(1).SetCellValue("完工数");
                                tRow1.CreateCell(2).SetCellValue("完工重");
                                tRow1.CreateCell(3).SetCellValue("开工数");
                                tRow1.CreateCell(4).SetCellValue("开工重");
                                tRow1.CreateCell(5).SetCellValue("进度重");
                                tRow1.CreateCell(6).SetCellValue("考核重");

                                bRow1.CreateCell(1).SetCellValue(data.Value.CompleteCount);
                                bRow1.CreateCell(2).SetCellValue(data.Value.CompleteWeight);
                                bRow1.CreateCell(3).SetCellValue(data.Value.BeginCount);
                                bRow1.CreateCell(4).SetCellValue(data.Value.BeginWeight);
                                bRow1.CreateCell(5).SetCellValue(data.Value.ProgressWeight);
                                bRow1.CreateCell(6).SetCellValue(data.Value.AuditWeight);
                            }
                            index++;
                        }
                    }
                };
                #endregion

                #region ======预处理
                ISheet sheet1 = workbook.GetSheet("预处理");
                currentSectionNames = schedule.ProcessUnits.Where(m => !String.IsNullOrEmpty(m.DealUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertCTProgress(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), CTProgressType.Pretreat, StartDate, EndDate);
                LoadData(currentData, sheet1);
                #endregion

                #region ======下料
                ISheet sheet2 = workbook.GetSheet("下料");
                currentSectionNames = schedule.ProcessUnits.Where(m => !String.IsNullOrEmpty(m.CuttUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertCTProgress(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), CTProgressType.Cutting, StartDate, EndDate);
                LoadData(currentData, sheet2);

                #endregion

                #region ======小组
                ISheet sheet3 = workbook.GetSheet("小组");
                currentSectionNames = schedule.ProcessUnits.Where(m => !String.IsNullOrEmpty(m.SmallGroupUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertCTProgress(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), CTProgressType.SmallGroup, StartDate, EndDate);
                LoadData(currentData, sheet3);
                #endregion

                #region ======中组
                ISheet sheet4 = workbook.GetSheet("中组");
                currentSectionNames = schedule.ProcessUnits.Where(m => !String.IsNullOrEmpty(m.MedGroupUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertCTProgress(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), CTProgressType.MediumGroup, StartDate, EndDate);
                LoadData(currentData, sheet4);
                #endregion

                #region ======中合A
                ISheet sheet5 = workbook.GetSheet("中合A");
                currentSectionNames = schedule.ProcessUnits.Where(m => !String.IsNullOrEmpty(m.MedAUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertCTProgress(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), CTProgressType.MediumMergeA, StartDate, EndDate, schedule);
                LoadData(currentData, sheet5);
                #endregion

                #region ======中涂
                ISheet sheet6 = workbook.GetSheet("中涂");
                currentSectionNames = schedule.ProcessUnits.Where(m => !String.IsNullOrEmpty(m.MidPaintUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertCTProgress(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), CTProgressType.MediumPainting, StartDate, EndDate, schedule);
                LoadData(currentData, sheet6);
                #endregion

                #region ======中合B
                ISheet sheet7 = workbook.GetSheet("中合B");
                currentSectionNames = schedule.ProcessUnits.Where(m => !String.IsNullOrEmpty(m.MedBUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertCTProgress(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), CTProgressType.MediumMergeB, StartDate, EndDate, schedule);
                LoadData(currentData, sheet7);
                #endregion

                #region ======大合
                ISheet sheet8 = workbook.GetSheet("大合");
                currentSectionNames = schedule.ProcessUnits.Where(m => !String.IsNullOrEmpty(m.BigUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertCTProgress(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), CTProgressType.LargeMerge, StartDate, EndDate, schedule);
                LoadData(currentData, sheet8);
                #endregion

                if (!Directory.Exists(ExcelOperation.CurrentDirectory + "/Export"))
                {
                    Directory.CreateDirectory(ExcelOperation.CurrentDirectory + "/Export");
                }
                LogHelper.Info("开始保存船体计划 " + saveFileName);
                //Write the stream data of workbook to the save directory
                using (FileStream exportFile = new FileStream(saveFileName, FileMode.Create))
                {
                    workbook.Write(exportFile);
                    exportFile.Close();
                }
                LogHelper.Info("结束保存船体计划 " + saveFileName);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("生成船体计划失败：", ex);
                return false;
            }
        }

        public static bool SaveXZPlan_Section(string saveFileName, XZSchedule schedule, Int32 year, Int32 month)
        {
            try
            {
                LogHelper.Info("导出舾装（分段）计划表开始，" + year + "年" + month + "月");
                var PlanTemplate = CurrentDirectory + @"\Template\生成计划（舾装_分段）.xls";
                if (!File.Exists(PlanTemplate))
                {
                    LogHelper.Error("舾装（分段）模板不存在，文件名：" + saveFileName);
                    MessageBox.Show("舾装（分段）模板不存在！", "提示");
                    return false;
                }
                IList<XZSectionPlan_Section> Plans = ConvertToXZPlan_Section(schedule);
                var StartDate = new DateTime(year, month, 1);
                var EndDate = new DateTime(year, month, DateTime.DaysInMonth(year, month));
                var ShipName = Plans.Count > 0 ? Plans.FirstOrDefault().ShipName : String.Empty;

                HSSFWorkbook workbook;
                LogHelper.Info("开始读取舾装(分段)计划模板，文件名：" + PlanTemplate);
                using (FileStream file = new FileStream(PlanTemplate, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                    file.Close();
                }
                LogHelper.Info("结束读取舾装(分段)计划模板，文件名：" + PlanTemplate);

                IList<XZSectionProgress_Section> currentData = new List<XZSectionProgress_Section>();
                IEnumerable<string> currentSectionNames = new List<string>();

                Action<IList<XZSectionProgress_Section>, ISheet> LoadData = (list, sheet) =>
                {
                    var dict = new XZProcessPlanDict_Section(list);
                    if (dict.Length > 0)
                    {
                        Int32 index = 0;
                        String title1 = String.Empty;
                        String title2 = String.Empty;
                        foreach (var data in dict.Dicts)
                        {
                            if (index == 0)
                            {
                                title1 = sheet.GetRow(index).GetCell(0).ToString();
                                title2 = sheet.GetRow(index + 1).GetCell(1).ToString();
                            }
                            else
                            {
                                #region 创建标题栏
                                var hrow1 = sheet.CreateRow(index);
                                hrow1.HeightInPoints = 27.75f;
                                hrow1.CreateCell(0).SetTitleStyle(workbook.CreateCellStyle(), workbook.CreateFont());
                                hrow1.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false);
                                var hrow2 = sheet.CreateRow(index + 1);
                                hrow2.HeightInPoints = 20;
                                hrow2.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false);
                                var hrow3 = sheet.CreateRow(index + 2);
                                hrow3.HeightInPoints = 20;
                                hrow3.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow3.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("分段名");
                                hrow3.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("重量");
                                hrow3.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("开工日");
                                hrow3.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("%");
                                hrow3.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("完工日");
                                hrow3.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("%");
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index, index, 0, 6));
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index + 1, index + 2, 0, 0));
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index + 1, index + 1, 1, 6));
                                hrow2.GetCell(0).SetCellValue("工程号");
                                #endregion
                            }
                            sheet.GetRow(index++).GetCell(0).SetCellValue(String.Format(title1, year, month));
                            sheet.GetRow(index++).GetCell(1).SetCellValue(String.Format(title2, data.Key));
                            Int32 startIndex = ++index;
                            for (int i = 0; i < data.Value.Data.Count; i++)
                            {
                                var row = sheet.CreateRow(index++);
                                var d1 = data.Value.Data[i];
                                row.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);

                                row.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.SectionName);
                                row.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.Weight);
                                row.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.BeginDate.ToString("yyyy-MM-dd"));
                                row.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.BeginPrecent);
                                row.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.EndDate.ToString("yyyy-MM-dd"));
                                row.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.EndPrecent);
                            }
                            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(startIndex, index - 1, 0, 0));
                            sheet.GetRow(startIndex).GetCell(0).SetCellValue(ShipName);
                            index++;
                            if (data.Value.Data.Count > 0)
                            {
                                var tRow1 = sheet.CreateRow(index++);
                                var bRow1 = sheet.CreateRow(index++);
                                tRow1.CreateCell(1).SetCellValue("完工数");
                                tRow1.CreateCell(2).SetCellValue("完工重");
                                tRow1.CreateCell(3).SetCellValue("开工数");
                                tRow1.CreateCell(4).SetCellValue("开工重");
                                tRow1.CreateCell(5).SetCellValue("进度重");
                                tRow1.CreateCell(6).SetCellValue("考核重");

                                bRow1.CreateCell(1).SetCellValue(data.Value.CompleteCount);
                                bRow1.CreateCell(2).SetCellValue(data.Value.CompleteWeight);
                                bRow1.CreateCell(3).SetCellValue(data.Value.BeginCount);
                                bRow1.CreateCell(4).SetCellValue(data.Value.BeginWeight);
                                bRow1.CreateCell(5).SetCellValue(data.Value.ProgressWeight);
                                bRow1.CreateCell(6).SetCellValue(data.Value.AuditWeight);
                            }
                            index++;
                        }
                    }
                };

                #region ======下料
                ISheet sheet2 = workbook.GetSheet("下料");
                //sheet2.GetRow(0).GetCell(0).SetFormatValue(Year, Month);
                currentSectionNames = schedule.ProcessUnits_Section.Where(m => !String.IsNullOrEmpty(m.CuttUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertXZProgress_Section(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), XZProgressType_Section.Cutting, StartDate, EndDate);

                LoadData(currentData, sheet2);
                #endregion

                #region ======成型
                ISheet sheet3 = workbook.GetSheet("成形");
                //sheet3.GetRow(0).GetCell(0).SetFormatValue(Year, Month);
                currentSectionNames = schedule.ProcessUnits_Section.Where(m => !String.IsNullOrEmpty(m.MoldingUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertXZProgress_Section(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), XZProgressType_Section.Molding, StartDate, EndDate);
                LoadData(currentData, sheet3);
                #endregion

                #region ======焊接
                ISheet sheet4 = workbook.GetSheet("焊接");
                //sheet4.GetRow(0).GetCell(0).SetFormatValue(Year, Month);
                currentSectionNames = schedule.ProcessUnits_Section.Where(m => !String.IsNullOrEmpty(m.WeldUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertXZProgress_Section(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), XZProgressType_Section.Weld, StartDate, EndDate);
                LoadData(currentData, sheet4);
                #endregion

                #region ======打磨
                ISheet sheet5 = workbook.GetSheet("打磨");
                //sheet5.GetRow(0).GetCell(0).SetFormatValue(Year, Month);
                currentSectionNames = schedule.ProcessUnits_Section.Where(m => !String.IsNullOrEmpty(m.PolishUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertXZProgress_Section(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), XZProgressType_Section.Polish, StartDate, EndDate);
                LoadData(currentData, sheet5);
                #endregion

                #region ======内场实验
                ISheet sheet6 = workbook.GetSheet("内场试验");
                sheet6.GetRow(0).GetCell(0).SetCellFormatValue(year, month);
                currentSectionNames = schedule.ProcessUnits_Section.Where(m => !String.IsNullOrEmpty(m.IntestUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertXZProgress_Section(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), XZProgressType_Section.Intest, StartDate, EndDate);
                LoadData(currentData, sheet6);
                #endregion

                #region ======预处理
                ISheet sheet1 = workbook.GetSheet("预处理");
                //sheet1.GetRow(0).GetCell(0).SetFormatValue(Year, Month);
                currentSectionNames = schedule.ProcessUnits_Section.Where(m => !String.IsNullOrEmpty(m.PretreatUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertXZProgress_Section(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), XZProgressType_Section.Pretreat, StartDate, EndDate);

                LoadData(currentData, sheet1);
                #endregion

                #region ======分段预装
                ISheet sheet7 = workbook.GetSheet("分段预装");
                sheet7.GetRow(0).GetCell(0).SetCellFormatValue(year, month);
                currentSectionNames = schedule.ProcessUnits_Section.Where(m => !String.IsNullOrEmpty(m.PreassembleUnit)).Select(m => m.SectionName).Distinct();
                currentData = ConvertXZProgress_Section(Plans.Where(m => currentSectionNames.Contains(m.SectionName)), XZProgressType_Section.Preassemble, StartDate, EndDate);
                LoadData(currentData, sheet7);
                #endregion

                if (!Directory.Exists(ExcelOperation.CurrentDirectory + "/Export"))
                {
                    Directory.CreateDirectory(ExcelOperation.CurrentDirectory + "/Export");
                }

                LogHelper.Info("开始保存舾装(分段)计划，文件名：" + saveFileName);
                //Write the stream data of workbook to the save directory
                using (FileStream exportFile = new FileStream(saveFileName, FileMode.Create))
                {
                    workbook.Write(exportFile);
                    exportFile.Close();
                }
                LogHelper.Info("结束保存舾装(分段)计划，文件名：" + saveFileName);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("生成舾装(分段)计划失败：", ex);
                return false;
            }
        }

        public static bool SaveXZPlan_Area(string saveFileName, XZSchedule schedule, int year, Int32 month)
        {
            try
            {
                LogHelper.Info("导出舾装（区域）计划表开始，" + year + "年" + month + "月");
                var PlanTemplate = CurrentDirectory + @"\Template\生成计划（舾装_区域）.xls";
                if (!File.Exists(PlanTemplate))
                {
                    LogHelper.Error("舾装（区域）模板不存在，文件名：" + saveFileName);
                    MessageBox.Show("舾装（区域）模板不存在！", "提示");
                    return false;
                }
                IList<XZSectionPlan_Area> Plans = ConvertToXZPlan_Area(schedule);
                var StartDate = new DateTime(year, month, 1);
                var EndDate = new DateTime(year, month, DateTime.DaysInMonth(year, month));
                var ShipName = Plans.Count > 0 ? Plans.FirstOrDefault().ShipName : String.Empty;

                HSSFWorkbook workbook;
                LogHelper.Info("开始读取舾装(区域)模板，文件名：" + PlanTemplate);
                using (FileStream file = new FileStream(PlanTemplate, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                    file.Close();
                }
                LogHelper.Info("结束读取舾装(区域)计划模板，文件名：" + PlanTemplate);

                IList<XZSectionProgress_Area> currentData = new List<XZSectionProgress_Area>();
                IEnumerable<string> currentSectionNames = new List<string>();
                Action<IList<XZSectionProgress_Area>, ISheet> LoadData = (list, sheet) =>
                {
                    var dict = new XZProcessPlanDict_Area(list);
                    if (dict.Length > 0)
                    {
                        Int32 index = 0;
                        String title1 = String.Empty;
                        String title2 = String.Empty;
                        foreach (var data in dict.Dicts)
                        {
                            if (index == 0)
                            {
                                title1 = sheet.GetRow(index).GetCell(0).ToString();
                                title2 = sheet.GetRow(index + 1).GetCell(1).ToString();
                            }
                            else
                            {
                                #region 创建标题栏
                                var hrow1 = sheet.CreateRow(index);
                                hrow1.HeightInPoints = 27.75f;
                                hrow1.CreateCell(0).SetTitleStyle(workbook.CreateCellStyle(), workbook.CreateFont());
                                hrow1.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false);
                                var hrow2 = sheet.CreateRow(index + 1);
                                hrow2.HeightInPoints = 20;
                                hrow2.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false);
                                var hrow3 = sheet.CreateRow(index + 2);
                                hrow3.HeightInPoints = 20;
                                hrow3.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow3.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("分段名");
                                hrow3.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("重量");
                                hrow3.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("开工日");
                                hrow3.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("%");
                                hrow3.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("完工日");
                                hrow3.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("%");
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index, index, 0, 6));
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index + 1, index + 2, 0, 0));
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index + 1, index + 1, 1, 6));
                                hrow2.GetCell(0).SetCellValue("工程号");
                                #endregion
                            }
                            sheet.GetRow(index++).GetCell(0).SetCellValue(String.Format(title1, year, month));
                            sheet.GetRow(index++).GetCell(1).SetCellValue(String.Format(title2, data.Key));
                            Int32 startIndex = ++index;
                            for (int i = 0; i < data.Value.Data.Count; i++)
                            {
                                var row = sheet.CreateRow(index++);
                                var d1 = data.Value.Data[i];
                                row.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);

                                row.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.AreaName);
                                row.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.Weight);
                                row.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.BeginDate.ToString("yyyy-MM-dd"));
                                row.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.BeginPrecent);
                                row.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.EndDate.ToString("yyyy-MM-dd"));
                                row.CreateCell(6).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.EndPrecent);
                            }
                            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(startIndex, index - 1, 0, 0));
                            sheet.GetRow(startIndex).GetCell(0).SetCellValue(ShipName);
                            index++;
                            if (data.Value.Data.Count > 0)
                            {
                                var tRow1 = sheet.CreateRow(index++);
                                var bRow1 = sheet.CreateRow(index++);
                                tRow1.CreateCell(1).SetCellValue("完工数");
                                tRow1.CreateCell(2).SetCellValue("完工重");
                                tRow1.CreateCell(3).SetCellValue("开工数");
                                tRow1.CreateCell(4).SetCellValue("开工重");
                                tRow1.CreateCell(5).SetCellValue("进度重");
                                tRow1.CreateCell(6).SetCellValue("考核重");

                                bRow1.CreateCell(1).SetCellValue(data.Value.CompleteCount);
                                bRow1.CreateCell(2).SetCellValue(data.Value.CompleteWeight);
                                bRow1.CreateCell(3).SetCellValue(data.Value.BeginCount);
                                bRow1.CreateCell(4).SetCellValue(data.Value.BeginWeight);
                                bRow1.CreateCell(5).SetCellValue(data.Value.ProgressWeight);
                                bRow1.CreateCell(6).SetCellValue(data.Value.AuditWeight);
                            }
                            index++;
                        }
                    }
                };

                #region ======成型
                ISheet sheet2 = workbook.GetSheet("成形");
                currentSectionNames = schedule.ProcessUnits_Area.Where(m => !String.IsNullOrEmpty(m.MoldingUnit)).Select(m => m.AreaName).Distinct();
                currentData = ConvertXZProgress_Area(Plans.Where(m => currentSectionNames.Contains(m.AreaName)), XZProgressType_Area.Molding, StartDate, EndDate);
                LoadData(currentData, sheet2);
                #endregion

                #region ======下料
                ISheet sheet3 = workbook.GetSheet("下料");
                currentSectionNames = schedule.ProcessUnits_Area.Where(m => !String.IsNullOrEmpty(m.CuttUnit)).Select(m => m.AreaName).Distinct();
                currentData = ConvertXZProgress_Area(Plans.Where(m => currentSectionNames.Contains(m.AreaName)), XZProgressType_Area.Cutting, StartDate, EndDate);
                LoadData(currentData, sheet3);
                #endregion

                #region ======焊接
                ISheet sheet4 = workbook.GetSheet("焊接");
                currentSectionNames = schedule.ProcessUnits_Area.Where(m => !String.IsNullOrEmpty(m.WeldUnit)).Select(m => m.AreaName).Distinct();
                currentData = ConvertXZProgress_Area(Plans.Where(m => currentSectionNames.Contains(m.AreaName)), XZProgressType_Area.Weld, StartDate, EndDate);
                LoadData(currentData, sheet4);
                #endregion

                #region ======打磨
                ISheet sheet5 = workbook.GetSheet("打磨");
                currentSectionNames = schedule.ProcessUnits_Area.Where(m => !String.IsNullOrEmpty(m.PolishUnit)).Select(m => m.AreaName).Distinct();
                currentData = ConvertXZProgress_Area(Plans.Where(m => currentSectionNames.Contains(m.AreaName)), XZProgressType_Area.Polish, StartDate, EndDate);
                LoadData(currentData, sheet5);
                #endregion

                #region ======内场实验
                ISheet sheet6 = workbook.GetSheet("内场试验");
                currentSectionNames = schedule.ProcessUnits_Area.Where(m => !String.IsNullOrEmpty(m.IntestUnit)).Select(m => m.AreaName).Distinct();
                currentData = ConvertXZProgress_Area(Plans.Where(m => currentSectionNames.Contains(m.AreaName)), XZProgressType_Area.Intest, StartDate, EndDate);
                LoadData(currentData, sheet6);
                #endregion

                #region ======预处理
                ISheet sheet1 = workbook.GetSheet("预处理");
                currentSectionNames = schedule.ProcessUnits_Area.Where(m => !String.IsNullOrEmpty(m.PretreatUnit)).Select(m => m.AreaName).Distinct();
                currentData = ConvertXZProgress_Area(Plans.Where(m => currentSectionNames.Contains(m.AreaName)), XZProgressType_Area.Pretreat, StartDate, EndDate);
                LoadData(currentData, sheet1);
                #endregion

                #region ======现场散装
                ISheet sheet7 = workbook.GetSheet("现场散装");
                currentSectionNames = schedule.ProcessUnits_Area.Where(m => !String.IsNullOrEmpty(m.BulkUnit)).Select(m => m.AreaName).Distinct();
                currentData = ConvertXZProgress_Area(Plans.Where(m => currentSectionNames.Contains(m.AreaName)), XZProgressType_Area.Bulk, StartDate, EndDate);
                LoadData(currentData, sheet7);
                #endregion

                if (!Directory.Exists(ExcelOperation.CurrentDirectory + "/Export"))
                {
                    Directory.CreateDirectory(ExcelOperation.CurrentDirectory + "/Export");
                }

                LogHelper.Info("开始保存舾装(区域)计划，文件名：" + saveFileName);
                //Write the stream data of workbook to the save directory
                using (FileStream exportFile = new FileStream(saveFileName, FileMode.Create))
                {
                    workbook.Write(exportFile);
                    exportFile.Close();
                }
                LogHelper.Info("开始保存舾装(区域)计划，文件名：" + saveFileName);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("生成舾装(区域)计划失败：", ex);
                return false;
            }
        }

        public static bool SaveXZPlan_Debug(string saveFileName, XZSchedule schedule, int year, Int32 month)
        {
            try
            {
                LogHelper.Info("导出舾装（调试）计划表开始，" + year + "年" + month + "月");
                var PlanTemplate = CurrentDirectory + @"\Template\生成计划（舾装_调试）.xls";
                if (!File.Exists(PlanTemplate))
                {
                    LogHelper.Error("舾装（调试）模板不存在，文件名：" + saveFileName);
                    MessageBox.Show("舾装（调试）模板不存在！", "提示");
                    return false;
                }
                IList<XZSectionPlan_Debug> Plans = ConvertToXZPlan_Debug(schedule);
                var StartDate = new DateTime(year, month, 1);
                var EndDate = new DateTime(year, month, DateTime.DaysInMonth(year, month));
                var ShipName = Plans.Count > 0 ? Plans.FirstOrDefault().ShipName : String.Empty;

                HSSFWorkbook workbook;
                LogHelper.Info("开始读取舾装(调试)计划模板，文件名：" + PlanTemplate);
                using (FileStream file = new FileStream(PlanTemplate, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                    file.Close();
                }
                LogHelper.Info("结束读取舾装(调试)计划模板，文件名：" + PlanTemplate);

                IList<XZSectionProgress_Debug> currentData = new List<XZSectionProgress_Debug>();
                IEnumerable<string> currentSectionNames = new List<string>();

                Action<IList<XZSectionProgress_Debug>, ISheet> LoadData = (list, sheet) =>
                {
                    var dict = new XZProcessPlanDict_Debug(list);
                    if (dict.Length > 0)
                    {
                        Int32 index = 0;
                        String title1 = String.Empty;
                        String title2 = String.Empty;
                        foreach (var data in dict.Dicts)
                        {
                            if (index == 0)
                            {
                                title1 = sheet.GetRow(index).GetCell(0).ToString();
                                title2 = sheet.GetRow(index + 1).GetCell(1).ToString();
                            }
                            else
                            {
                                #region 创建标题栏
                                var hrow1 = sheet.CreateRow(index);
                                hrow1.HeightInPoints = 27.75f;
                                hrow1.CreateCell(0).SetTitleStyle(workbook.CreateCellStyle(), workbook.CreateFont());
                                hrow1.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow1.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false);
                                var hrow2 = sheet.CreateRow(index + 1);
                                hrow2.HeightInPoints = 20;
                                hrow2.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow2.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false);
                                var hrow3 = sheet.CreateRow(index + 2);
                                hrow3.HeightInPoints = 20;
                                hrow3.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);
                                hrow3.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("分段名");
                                //hrow3.CreateCell(2).SetStyle(workbook.CreateCellStyle(), false).SetCellValue("重量");
                                hrow3.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("开工日");
                                hrow3.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("%");
                                hrow3.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("完工日");
                                hrow3.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), false).SetCellValue("%");
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index, index, 0, 5));
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index + 1, index + 2, 0, 0));
                                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(index + 1, index + 1, 1, 5));
                                hrow2.GetCell(0).SetCellValue("工程号");
                                #endregion
                            }
                            sheet.GetRow(index++).GetCell(0).SetCellValue(String.Format(title1, year, month));
                            sheet.GetRow(index++).GetCell(1).SetCellValue(String.Format(title2, data.Key));
                            Int32 startIndex = ++index;
                            for (int i = 0; i < data.Value.Data.Count; i++)
                            {
                                var row = sheet.CreateRow(index++);
                                var d1 = data.Value.Data[i];
                                row.CreateCell(0).SetCellStyle(workbook.CreateCellStyle(), false);

                                row.CreateCell(1).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.ProjectName);
                                row.CreateCell(2).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.BeginDate.ToString("yyyy-MM-dd"));
                                row.CreateCell(3).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.BeginPrecent);
                                row.CreateCell(4).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.EndDate.ToString("yyyy-MM-dd"));
                                row.CreateCell(5).SetCellStyle(workbook.CreateCellStyle(), d1.IsComplete).SetCellValue(d1.EndPrecent);
                            }
                            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(startIndex, index - 1, 0, 0));
                            sheet.GetRow(startIndex).GetCell(0).SetCellValue(ShipName);
                            index++;
                            if (data.Value.Data.Count > 0)
                            {
                                var tRow1 = sheet.CreateRow(index++);
                                var bRow1 = sheet.CreateRow(index++);
                                tRow1.CreateCell(1).SetCellValue("完工数");
                                tRow1.CreateCell(2).SetCellValue("完工重");
                                tRow1.CreateCell(3).SetCellValue("开工数");
                                tRow1.CreateCell(4).SetCellValue("开工重");
                                //tRow1.CreateCell(5).SetCellValue("进度重");
                                //tRow1.CreateCell(6).SetCellValue("考核重");

                                bRow1.CreateCell(1).SetCellValue(data.Value.CompleteCount);
                                bRow1.CreateCell(2).SetCellValue(String.Empty);
                                bRow1.CreateCell(3).SetCellValue(data.Value.BeginCount);
                                bRow1.CreateCell(4).SetCellValue(String.Empty);
                                //bRow1.CreateCell(5).SetCellValue(data.Value.ProgressWeight);
                                //bRow1.CreateCell(6).SetCellValue(data.Value.AuditWeight);
                            }
                            index++;
                        }
                    }
                };

                #region ======调试
                ISheet sheet1 = workbook.GetSheet("调试");
                currentSectionNames = schedule.ProcessUnits_Debug.Where(m => !String.IsNullOrEmpty(m.DebuggingUnit)).Select(m => m.ProjectName).Distinct();
                currentData = ConvertXZProgress_Debug(Plans.Where(m => currentSectionNames.Contains(m.ProjectName)), XZProgressType_Debug.Debugging, StartDate, EndDate);

                LoadData(currentData, sheet1);
                #endregion

                if (!Directory.Exists(ExcelOperation.CurrentDirectory + "/Export"))
                {
                    Directory.CreateDirectory(ExcelOperation.CurrentDirectory + "/Export");
                }

                LogHelper.Info("开始保存舾装(调试)计划，文件名：" + saveFileName);
                //Write the stream data of workbook to the save directory
                using (FileStream exportFile = new FileStream(saveFileName, FileMode.Create))
                {
                    workbook.Write(exportFile);
                    exportFile.Close();
                }
                LogHelper.Info("结束保存舾装(调试)计划，文件名：" + saveFileName);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("生成舾装(调试)计划失败：", ex);
                return false;
            }
        }

        public static string GetProcessName(string sectionName, string unitName)
        {
            string Xmlpath = AppDomain.CurrentDomain.BaseDirectory + @"\ProcessUnit.xml";
            try
            {
                if (File.Exists(Xmlpath))
                {
                    XDocument xml = XDocument.Load(Xmlpath);
                    XElement xe = xml.Root.XPathSelectElements("/Project/Section[@Name='" + sectionName + "']/Unit[@Name='" + unitName + "']").FirstOrDefault();
                    if (xe != null)
                    {
                        return xe.Value;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return String.Empty;
        }

        private static IList<CTSectionProgress> ConvertCTProgress(IEnumerable<CTSectionPlan> plans, CTProgressType type, DateTime begindate, DateTime enddate, CTSchedule schedule = null)
        {
            IList<CTSectionProgress> Progresses = new List<CTSectionProgress>();
            foreach (var plan in plans)
            {
                var sectionPro = CTSectionProgress.GetProgerssByPlan(plan, type, begindate, enddate);
                if (sectionPro != null)
                {
                    Progresses.Add(sectionPro);
                }
            }
            switch (type)
            {
                case CTProgressType.MediumMergeA:
                    {
                        IList<CTSectionProgress> NewProgresses = new List<CTSectionProgress>();
                        foreach (var re in schedule.MediumMergeARelates)
                        {
                            var sp = plans.Where(m => re.SectionNames.Contains(m.SectionName));
                            var d = Progresses.Where(m => re.SectionNames.Contains(m.SectionName));
                            if (d.Count() > 0)
                            {
                                var p = new CTSectionProgress();
                                p.ShipName = re.ShipName;
                                p.SectionName = re.MediumMergeName;
                                p.PlanStartDate = sp.Min(m => m.MediumMergeAStart.Value);
                                p.PlanEndDate = sp.Max(m => m.MediumMergeAStop.Value);
                                p.BeginDate = d.Min(m => m.BeginDate);
                                p.EndDate = d.Max(m => m.EndDate);
                                p.BeginPrecent = (p.BeginDate - p.PlanStartDate).Days * 100 / p.PlanDays;
                                p.EndPrecent = (p.EndDate.AddDays(1) - p.PlanStartDate).Days * 100 / p.PlanDays;
                                p.Weight = sp.Select(m => m.Weight).Aggregate((m, n) => m + n);
                                p.UnitName = sp.FirstOrDefault().Units.MedAUnit;
                                NewProgresses.Add(p);
                            }
                        }
                        return NewProgresses;
                    }
                case CTProgressType.MediumPainting:
                    {
                        foreach (var re in schedule.MediumMergeARelates)
                        {
                            var sp = plans.Where(m => re.SectionNames.Contains(m.SectionName));
                            var d = Progresses.Where(m => re.SectionNames.Contains(m.SectionName)).ToArray();
                            if (d.Length > 0)
                            {
                                var p = new CTSectionProgress();
                                p.ShipName = re.ShipName;
                                p.SectionName = re.MediumMergeName;
                                p.PlanStartDate = sp.Min(m => m.MediumPaintingStart.Value);
                                p.PlanEndDate = sp.Max(m => m.MediumPaintingStop.Value);
                                p.BeginDate = d.Min(m => m.BeginDate);
                                p.EndDate = d.Max(m => m.EndDate);
                                p.BeginPrecent = (p.BeginDate - p.PlanStartDate).Days * 100 / p.PlanDays;
                                p.EndPrecent = (p.EndDate.AddDays(1) - p.PlanStartDate).Days * 100 / p.PlanDays;
                                p.Weight = sp.Select(m => m.Weight).Aggregate((m, n) => m + n);
                                p.UnitName = sp.FirstOrDefault().Units.MidPaintUnit;
                                foreach (var n in d)
                                {
                                    Progresses.Remove(n);
                                }
                                Progresses.Add(p);
                            }
                        }
                        break;
                    }
                case CTProgressType.MediumMergeB:
                    {
                        IList<CTSectionProgress> NewProgresses = new List<CTSectionProgress>();
                        foreach (var re in schedule.MediumMergeBRelates)
                        {
                            var sp = plans.Where(m => re.SectionNames.Contains(m.SectionName));
                            var d = Progresses.Where(m => re.SectionNames.Contains(m.SectionName));
                            if (d.Count() > 0)
                            {
                                var p = new CTSectionProgress();
                                p.ShipName = re.ShipName;
                                p.SectionName = re.MediumMergeName;
                                p.PlanStartDate = sp.Min(m => m.MediumMergeBStart.Value);
                                p.PlanEndDate = sp.Max(m => m.MediumMergeBStop.Value);
                                p.BeginDate = d.Min(m => m.BeginDate);
                                p.EndDate = d.Max(m => m.EndDate);
                                p.BeginPrecent = (p.BeginDate - p.PlanStartDate).Days * 100 / p.PlanDays;
                                p.EndPrecent = (p.EndDate.AddDays(1) - p.PlanStartDate).Days * 100 / p.PlanDays;
                                p.Weight = sp.Select(m => m.Weight).Aggregate((m, n) => m + n);
                                p.UnitName = sp.FirstOrDefault().Units.MedBUnit;
                                NewProgresses.Add(p);
                            }
                        }
                        return NewProgresses;
                    }
                case CTProgressType.LargeMerge:
                    {
                        foreach (var re in schedule.MediumMergeBRelates)
                        {
                            var sp = plans.Where(m => re.SectionNames.Contains(m.SectionName));
                            var d = Progresses.Where(m => re.SectionNames.Contains(m.SectionName)).ToArray();
                            if (d.Length > 0)
                            {
                                var p = new CTSectionProgress();
                                p.ShipName = re.ShipName;
                                p.SectionName = re.MediumMergeName;
                                p.PlanStartDate = sp.Min(m => m.LargeMergeStart.Value);
                                p.PlanEndDate = sp.Max(m => m.LargeMergeStop.Value);
                                p.BeginDate = d.Min(m => m.BeginDate);
                                p.EndDate = d.Max(m => m.EndDate);
                                p.BeginPrecent = (p.BeginDate - p.PlanStartDate).Days * 100 / p.PlanDays;
                                p.EndPrecent = (p.EndDate.AddDays(1) - p.PlanStartDate).Days * 100 / p.PlanDays;
                                p.Weight = sp.Select(m => m.Weight).Aggregate((m, n) => m + n);
                                p.UnitName = sp.FirstOrDefault().Units.BigUnit;
                                foreach (var n in d)
                                {
                                    Progresses.Remove(n);
                                }
                                Progresses.Add(p);
                            }
                        }
                        break;
                    }
                default:
                    break;
            }
            return Progresses;
        }

        private static IList<XZSectionProgress_Section> ConvertXZProgress_Section(IEnumerable<XZSectionPlan_Section> plans, XZProgressType_Section type, DateTime begindate, DateTime enddate)
        {
            IList<XZSectionProgress_Section> Progresses = new List<XZSectionProgress_Section>();
            foreach (var plan in plans)
            {
                var sectionPro = XZSectionProgress_Section.GetProgerssByPlan(plan, type, begindate, enddate);
                if (sectionPro != null)
                {
                    Progresses.Add(sectionPro);
                }
            }
            return Progresses.ToList();
        }

        private static IList<XZSectionProgress_Area> ConvertXZProgress_Area(IEnumerable<XZSectionPlan_Area> plans, XZProgressType_Area type, DateTime begindate, DateTime enddate)
        {
            IList<XZSectionProgress_Area> Progresses = new List<XZSectionProgress_Area>();
            foreach (var plan in plans)
            {
                var sectionPro = XZSectionProgress_Area.GetProgerssByPlan(plan, type, begindate, enddate);
                if (sectionPro != null)
                {
                    Progresses.Add(sectionPro);
                }
            }
            return Progresses.ToList();
        }

        private static IList<XZSectionProgress_Debug> ConvertXZProgress_Debug(IEnumerable<XZSectionPlan_Debug> plans, XZProgressType_Debug type, DateTime begindate, DateTime enddate)
        {
            IList<XZSectionProgress_Debug> Progresses = new List<XZSectionProgress_Debug>();
            foreach (var plan in plans)
            {
                var sectionPro = XZSectionProgress_Debug.GetProgerssByPlan(plan, type, begindate, enddate);
                if (sectionPro != null)
                {
                    Progresses.Add(sectionPro);
                }
            }
            return Progresses.ToList();
        }

        public static bool SaveTWSectionArrange(string saveFileName, TWSchedule schedule, Int32 year, Int32 month)
        {
            FetalLayout fetalLayout = new FetalLayout(schedule);

            IList<TWSectionArrange> allArrange = fetalLayout.GetAllSectionArrange();
            IList<TWSectionArrange> singleMonthArrange = fetalLayout.GetSectionArrangeByMonth(year, month);
            IList<TWSectionInfo> invalidSections = fetalLayout.GetInvalidSections();
            
            try
            {
                LogHelper.Info("导出胎位流转信息开始");
                var SummaryTemplate = CurrentDirectory + @"\Template\生成胎位流转信息.xls";
                if (!File.Exists(SummaryTemplate))
                {
                    LogHelper.Error("胎位流转信息模板不存在，文件名：" + SummaryTemplate);
                    MessageBox.Show("胎位流转信息模板不存在！", "提示");
                    return false;
                }
                HSSFWorkbook workbook;
                LogHelper.Info("开始读取胎位流转信息模板，文件名：" + SummaryTemplate);
                using (FileStream file = new FileStream(SummaryTemplate, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                    file.Close();
                }
                LogHelper.Info("结束胎位流转信息模板，文件名：" + SummaryTemplate);

                // 对数据源进行逻辑匹配运算返回可行数据
                ISheet Sheet1 = workbook.GetSheet("每个胎位流转");
                ISheet Sheet2 = workbook.GetSheet("每月每个胎位流转");
                if (Sheet1 == null || Sheet2 == null) {
                    LogHelper.Info("胎位流转信息模板格式错误，文件名：" + SummaryTemplate);
                    MessageBox.Show("胎位流转信息模板格式错误！", "提示");
                    return false;
                }

                // sheet1
                for (int i = 0; i < allArrange.Count; i++)
                {
                    var row = Sheet1.CreateRow(i + 3);
                    // 序号自增长,添加船号
                    //row.CreateCell(0).SetCellValue(allArrange[i].ID.ToString());
                    row.CreateCell(0).SetCellValue(i + 1);
                    row.CreateCell(1).SetCellValue(allArrange[i].Position);
                    row.CreateCell(2).SetCellValue(allArrange[i].ShipName);
                    row.CreateCell(3).SetCellValue(allArrange[i].SectionName);
                    row.CreateCell(4).SetCellValue(allArrange[i].UpFetalDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(5).SetCellValue(allArrange[i].DownFetalDate.ToString("yyyy-MM-dd"));
                }

                for (int i = 0; i < invalidSections.Count; i++)
                {
                    var row = Sheet1.CreateRow(i + allArrange.Count + 3);
                    //row.CreateCell(0).SetCellValue(invalidSections[i].ID.ToString());
                    row.CreateCell(0).SetCellValue(i + 1);
                    row.CreateCell(1).SetCellValue(invalidSections[i].InvalidMessage);
                    row.CreateCell(2).SetCellValue(invalidSections[i].ShipName);
                    row.CreateCell(3).SetCellValue(invalidSections[i].SectionName);
                    row.CreateCell(4).SetCellValue(invalidSections[i].UpFetalDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(5).SetCellValue(invalidSections[i].DownFetalDate.ToString("yyyy-MM-dd"));
                }
                
                // sheet2
                string title = Sheet2.GetRow(0).GetCell(0).ToString();
                Sheet2.GetRow(0).GetCell(0).SetCellValue(String.Format(title,year, month));
                for (int j = 0; j < singleMonthArrange.Count; j++) {
                    var row = Sheet2.CreateRow(j + 3);
                    //row.CreateCell(0).SetCellValue(singleMonthArrange[j].ID.ToString());
                    row.CreateCell(0).SetCellValue(j + 1);
                    row.CreateCell(1).SetCellValue(singleMonthArrange[j].Position);
                    row.CreateCell(2).SetCellValue(singleMonthArrange[j].ShipName);
                    row.CreateCell(3).SetCellValue(singleMonthArrange[j].SectionName);
                    row.CreateCell(4).SetCellValue(singleMonthArrange[j].UpFetalDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(5).SetCellValue(singleMonthArrange[j].DownFetalDate.ToString("yyyy-MM-dd"));
                }

                if (!Directory.Exists(ExcelOperation.CurrentDirectory + "/Export"))
                {
                    Directory.CreateDirectory(ExcelOperation.CurrentDirectory + "/Export");
                }
                LogHelper.Info("开始保存胎位流转信息，文件名：" + saveFileName);
                //Write the stream data of workbook to the save directory
                using (FileStream exportFile = new FileStream(saveFileName, FileMode.Create))
                {
                    workbook.Write(exportFile);
                    exportFile.Close();
                }
                LogHelper.Info("结束保存胎位流转信息，文件名：" + saveFileName);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("导出胎位流转信息失败：", ex);
                return false;
            }
        }

        public static bool SaveAllTWSectionArrange(string saveFileName, TWSchedule schedule)
        {
            FetalLayout fetalLayout = new FetalLayout(schedule);

            IList<TWSectionArrange> allArrange = fetalLayout.GetAllSectionArrange();
            IList<TWSectionInfo> invalidSections = fetalLayout.GetInvalidSections();

            try
            {
                LogHelper.Info("导出胎位流转信息开始");
                var SummaryTemplate = CurrentDirectory + @"\Template\生成胎位流转信息.xls";
                if (!File.Exists(SummaryTemplate))
                {
                    LogHelper.Error("胎位流转信息模板不存在，文件名：" + SummaryTemplate);
                    MessageBox.Show("胎位流转信息模板不存在！", "提示");
                    return false;
                }
                HSSFWorkbook workbook;
                LogHelper.Info("开始读取胎位流转信息模板，文件名：" + SummaryTemplate);
                using (FileStream file = new FileStream(SummaryTemplate, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                    file.Close();
                }
                LogHelper.Info("结束胎位流转信息模板，文件名：" + SummaryTemplate);

                // 对数据源进行逻辑匹配运算返回可行数据
                ISheet Sheet1 = workbook.GetSheet("每个胎位流转");
                ISheet Sheet2 = workbook.GetSheet("每月每个胎位流转");
                if (Sheet1 == null || Sheet2 == null)
                {
                    LogHelper.Info("胎位流转信息模板格式错误，文件名：" + SummaryTemplate);
                    MessageBox.Show("胎位流转信息模板格式错误！", "提示");
                    return false;
                }

                // sheet1
                for (int i = 0; i < allArrange.Count; i++)
                {
                    var row = Sheet1.CreateRow(i + 3);
                    //row.CreateCell(0).SetCellValue(allArrange[i].ID.ToString());
                    row.CreateCell(0).SetCellValue(i + 1);
                    row.CreateCell(1).SetCellValue(allArrange[i].Position);
                    row.CreateCell(2).SetCellValue(allArrange[i].ShipName);
                    row.CreateCell(3).SetCellValue(allArrange[i].SectionName);
                    row.CreateCell(4).SetCellValue(allArrange[i].UpFetalDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(5).SetCellValue(allArrange[i].DownFetalDate.ToString("yyyy-MM-dd"));
                }

                for (int i = 0; i < invalidSections.Count; i++)
                {
                    var row = Sheet1.CreateRow(i + allArrange.Count + 3);
                    //row.CreateCell(0).SetCellValue(invalidSections[i].ID.ToString());
                    row.CreateCell(0).SetCellValue(i + 1);
                    row.CreateCell(1).SetCellValue(invalidSections[i].InvalidMessage);
                    row.CreateCell(2).SetCellValue(invalidSections[i].ShipName);
                    row.CreateCell(3).SetCellValue(invalidSections[i].SectionName);
                    row.CreateCell(4).SetCellValue(invalidSections[i].UpFetalDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(5).SetCellValue(invalidSections[i].DownFetalDate.ToString("yyyy-MM-dd"));
                }

                //删除 sheet2
                workbook.RemoveSheetAt(1);

                if (!Directory.Exists(ExcelOperation.CurrentDirectory + "/Export"))
                {
                    Directory.CreateDirectory(ExcelOperation.CurrentDirectory + "/Export");
                }
                LogHelper.Info("开始保存胎位流转信息，文件名：" + saveFileName);
                //Write the stream data of workbook to the save directory
                using (FileStream exportFile = new FileStream(saveFileName, FileMode.Create))
                {
                    workbook.Write(exportFile);
                    exportFile.Close();
                }
                LogHelper.Info("结束保存胎位流转信息，文件名：" + saveFileName);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("导出胎位流转信息失败：", ex);
                return false;
            }
        }
    }
}
